#include "widget.h"
#include "dialog.h"
#include "health_set.h"
#include<QDebug>
typedef struct _WTSINFOEX_LEVEL1_W {
  ULONG                  SessionId;
  WTS_CONNECTSTATE_CLASS SessionState;
  LONG                   SessionFlags;
  WCHAR                  WinStationName[WINSTATIONNAME_LENGTH + 1];
  WCHAR                  UserName[USERNAME_LENGTH + 1];
  WCHAR                  DomainName[DOMAIN_LENGTH + 1];
  LARGE_INTEGER          LogonTime;
  LARGE_INTEGER          ConnectTime;
  LARGE_INTEGER          DisconnectTime;
  LARGE_INTEGER          LastInputTime;
  LARGE_INTEGER          CurrentTime;
  DWORD                  IncomingBytes;
  DWORD                  OutgoingBytes;
  DWORD                  IncomingFrames;
  DWORD                  OutgoingFrames;
  DWORD                  IncomingCompressedBytes;
  DWORD                  OutgoingCompressedBytes;
} WTSINFOEX_LEVEL1_W, *PWTSINFOEX_LEVEL1_W;

typedef union _WTSINFOEX_LEVEL_W {
  WTSINFOEX_LEVEL1_W WTSInfoExLevel1;
} WTSINFOEX_LEVEL_W, *PWTSINFOEX_LEVEL_W;

typedef struct _WTSINFOEXW {
    DWORD             Level;
    WTSINFOEX_LEVEL_W Data;
} WTSINFOEXW, * PWTSINFOEXW;
bool IsSessionUnLocked()
{
    typedef BOOL(PASCAL* WTSQuerySessionInformation)(HANDLE hServer, DWORD SessionId, WTS_INFO_CLASS WTSInfoClass, LPTSTR* ppBuffer, DWORD* pBytesReturned);
    typedef void (PASCAL* WTSFreeMemory)(PVOID pMemory);

    WTSINFOEXW * pInfo = NULL;
    WTS_INFO_CLASS wtsic = WTSSessionInfoEx;
    bool bRet = false;
    LPTSTR ppBuffer = NULL;
    DWORD dwBytesReturned = 0;
    LONG dwFlags = 0;
    WTSQuerySessionInformation pWTSQuerySessionInformation = NULL;
    WTSFreeMemory pWTSFreeMemory = NULL;

    HMODULE hLib = LoadLibrary(L"wtsapi32.dll");
    if (!hLib)
    {
        return false;
    }
    pWTSQuerySessionInformation = (WTSQuerySessionInformation)GetProcAddress(hLib, "WTSQuerySessionInformationW");
    if (pWTSQuerySessionInformation)
    {
        pWTSFreeMemory = (WTSFreeMemory)GetProcAddress(hLib, "WTSFreeMemory");
        if (pWTSFreeMemory != NULL)
        {
            DWORD dwSessionID = WTSGetActiveConsoleSessionId();
            if (pWTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, dwSessionID, wtsic, &ppBuffer, &dwBytesReturned))
            {
                if (dwBytesReturned > 0)
                {
                    pInfo = (WTSINFOEXW*)ppBuffer;
                    if (pInfo->Level == 1)
                    {
                        dwFlags = pInfo->Data.WTSInfoExLevel1.SessionFlags;
                    }
                    if (dwFlags == 0)
                    {
                        bRet = true;
                    }
                }
                pWTSFreeMemory(ppBuffer);
                ppBuffer = NULL;
            }
        }
    }
    if (hLib != NULL)
    {
        FreeLibrary(hLib);
    }
    return bRet;
}
Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    calendar = new Calendar;
    calendar->hide();
    dialog2 = new health_set;
    connect(dialog2, SIGNAL(sendData(int)), this, SLOT(receiveData(int)));

    setWindowFlag(Qt::FramelessWindowHint);
    setWindowFlags(windowFlags() | Qt::WindowStaysOnTopHint);
    setAttribute(Qt::WA_TranslucentBackground);
    setMouseTracking(true);
    setMinimumSize(1400, 1400);

    // 创建右键菜单
    contextMenu = new QMenu(this);

    // 添加菜单项
    QAction *menuItem1 = contextMenu->addAction("打开日历");
    QAction *menuItem3 = contextMenu->addAction("健康时间设置");
    QAction *menuItem2 = contextMenu->addAction("退出");


    // 连接菜单项的槽函数
    connect(menuItem1, &QAction::triggered, this, &Widget::handleMenuItem1);
    connect(menuItem2, &QAction::triggered, this, &Widget::handleMenuItem2);
    connect(menuItem3, &QAction::triggered, this, &Widget::handleMenuItem3);

    // 连接右键点击事件
    connect(this, &Widget::customContextMenuRequested, this, &Widget::showContextMenu);

    // 启用右键菜单
    setContextMenuPolicy(Qt::CustomContextMenu);

//    // 创建系统托盘图标
//    trayIcon = new QSystemTrayIcon(this);
//    trayIcon->setIcon(QIcon(":/png/ui/1.png")); // 设置托盘图标

//    // 创建系统托盘菜单
//    trayMenu = new QMenu(this);

//    // 添加菜单项
//    QAction *exitAction = trayMenu->addAction("退出程序");
//    connect(exitAction, &QAction::triggered, this, &Widget::exitApplication);

//    // 设置系统托盘菜单
//    trayIcon->setContextMenu(trayMenu);

//    // 显示系统托盘图标
//    trayIcon->show();

//    // 连接系统托盘图标的槽函数
//    connect(trayIcon, &QSystemTrayIcon::activated, this, &Widget::trayIconActivated);

    currentImageIndex = 6; // 初始显示6.png

    // 连接鼠标点击事件到新的槽函数
    connect(this, &Widget::mouseLeftButtonClicked, this, &Widget::changeImage);

//    // 隐藏主任务栏窗口
//    setWindowFlags(Qt::FramelessWindowHint | Qt::Tool);
//    setAttribute(Qt::WA_TranslucentBackground);
//    setMouseTracking(true);

    hlayout = new QHBoxLayout(this);
    l = new QLabel();
    hlayout->addWidget(l);
    idx = 6;
    l->setStyleSheet(QString("background: url(:/png/ui/%1.png) no-repeat;").arg(idx));



    textLabel = new QLabel(this); // 初始化 textLabel
    textLabel->setAlignment(Qt::AlignHCenter);
    textLabel->setGeometry(0, 0, 300, 35);
    textLabel->setStyleSheet("background-color: rgba(255, 255, 255, 255);");


    QFont font;
    font.setPointSize(10);
    textLabel->setFont(font);
    textLabel->setWordWrap(true);
    textLabel->setText("欢迎回来");


    // 初始化 timer
    timer = new QTimer(this);



    connect(timer, &QTimer::timeout, this , [this]() {
        textLabel->clear();
        textLabel->hide();
        timer->stop();
    });


    displayTextFromLine(idx);

//    timer2 = new QTimer(this);
//    timer2->setInterval(100);
//    timer2->start();

//    connect(timer2, &QTimer::timeout, this , [this]() {
//        timer2->stop();
//        trayIconActivated(QSystemTrayIcon::Trigger);
//        timer2->setInterval(100);
//        timer2->start();
//    });

    remind_timer = new QTimer;
    connect(remind_timer,&QTimer::timeout,this,&Widget::timeoutSlot);
    remind_timer->start(health_time);



    loop_timer = new QTimer;
    // 设置计时器每隔1秒触发一次
    loop_timer->setInterval(1000);
    flag=0;
    // 连接计时器的timeout()信号到槽函数
    connect(loop_timer, &QTimer::timeout, [&]() {
        int result = IsSessionUnLocked();
        if (result) {
            // 函数返回0，停止计时器
            remind_timer->stop();
            flag = 1;
        } else if (!result&& flag) {
            // 函数返回1，重启计时器
            remind_timer->start(health_time);
            flag = 0;
        }
    });

    // 启动计时器
    loop_timer->start();
}

void Widget::timeoutSlot()
{
    dialog = new Dialog;
    dialog->show();
}

void Widget::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        // 记录鼠标按下时的位置
        lastMousePos = event->globalPos();
        isDragging = false; // 将拖动标志设置为 false

    }
    diff_ = event->globalPos() - this->pos();
}

void Widget::mouseMoveEvent(QMouseEvent *event)
{
    if (event->buttons() & Qt::LeftButton) {
        // 计算鼠标移动距离
        QPoint diff = event->globalPos() - lastMousePos;

        if (diff.manhattanLength() > QApplication::startDragDistance()) {
            isDragging = true; // 如果移动距离超过阈值，将拖动标志设置为 true
        }
    }
    this->move(event->globalPos() - this->diff_);
}

void Widget::mouseReleaseEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        if (!isDragging) {
            // 鼠标左键单击，执行图片切换逻辑
            emit mouseLeftButtonClicked();

        }

        isDragging = false; // 重置拖动标志
    }
    diff_ = QPoint();
}


void Widget::updateLabelBackground()
{
    idx = 6;
    //idx = (idx + 1) % 2971 + 1;
    l->setStyleSheet(QString("background: url(:/png/ui/%1.png) no-repeat;").arg(idx));
}

void Widget::showContextMenu(const QPoint &pos)
{
    rightClickPos = pos;
    contextMenu->exec(mapToGlobal(pos));
}

void Widget::handleMenuItem1()
{
    // 在这里处理菜单项1的操作

    calendar->show();
}

void Widget::handleMenuItem2()
{
    // 在这里处理菜单项2的操作

    // 处理退出程序

    QApplication::quit();
}

void Widget::handleMenuItem3()
{
    // 在这里处理菜单项3的操作
    dialog2->show();
}


void Widget::receiveData(int data) {
    // 在这里处理接收到的数据
    if(data==0)
    {
        remind_timer->stop();
        health_time = 60000;
        remind_timer->start(health_time);
    }
    else if(data==1)
    {
        remind_timer->stop();
        health_time = 1800000;
        remind_timer->start(health_time);
    }
    else if(data==2)
    {
        remind_timer->stop();
        health_time = 2700000;
        remind_timer->start(health_time);
    }
    else if(data==3)
    {
        remind_timer->stop();
        health_time = 3600000;
        remind_timer->start(health_time);
    }

}
void Widget::trayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
    if (reason == QSystemTrayIcon::Trigger) {
        // 处理单击事件
        showNormal(); // 恢复窗口显示
        activateWindow();
    }
}


void Widget::exitApplication()
{
    // 处理退出程序
    QApplication::quit();
}

void Widget::changeImage()
{
    // 切换图片，这里可以根据你的图片文件命名规则来更新图片
    currentImageIndex = (currentImageIndex == 7) ? 2 : currentImageIndex+1;
    l->setStyleSheet(QString("background: url(:/png/ui/%1.png) no-repeat;").arg(currentImageIndex));
    displayTextFromLine(currentImageIndex);
}

void Widget::displayTextFromLine(int lineNumber)
{
    timer->stop();
    timer->setInterval(5000);
    timer->start();
    textLabel->show();

    QString filePath =":/png/ui/sentences.txt";
    QFile file(filePath);
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream in(&file);
        int currentLine = 1;
        QString line;

        while (currentLine < lineNumber && !in.atEnd()) {
            line = in.readLine();
            currentLine++;
        }

        if (currentLine == lineNumber) {
            textLabel->setText(line);
        }

        file.close();
    }


}

//Widget::drinkwater(){
//    timer->stop();
//    timer->setInterval(10000);
//    timer->start();
//    textLabel->setText("该喝水了");
//    textLabel->show();
//}

Widget::~Widget()
{
    delete calendar;
    // 清理系统托盘图标
    if (trayIcon) {
        trayIcon->hide();
        delete trayIcon;
    }
    free(textLabel);
    free(timer);
}
